/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.jr.wx.video.downloadagent.handler;

import cn.ac.iie.di.ban.jr.wx.video.downloadagent.common.RuntimeEnv;
import cn.ac.iie.di.ban.jr.wx.video.downloadagent.utils.FileTools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class ParserFileHandler implements Runnable {

    static private final Logger logger = Logger.getLogger(ParserFileHandler.class.getName());
    private String requestDir;

    public ParserFileHandler(String requestDir) {
        this.requestDir = requestDir;
    }

    @Override
    public void run() {
        logger.info("the parser file path is " + requestDir);
        while (true) {
            try {
                File localFile = new File(requestDir);
                if (localFile.exists()) {
                    File[] localFilelist = localFile.listFiles();
                    int length = localFilelist.length;
//                    logger.info(requestDir + " has " + length + " files. And the LOCALFILESIZE is : " + localFileSize);

                    List<File> finalList = new ArrayList<File>();//最终解析列表
                    int count = 0;
                    if (length > 0) {
                        for (int i = 0; i < localFilelist.length; i++) {
                            if (localFilelist[i].isFile()) {
                                finalList.add(localFilelist[i]);
                                count++;
                            }

                            if (count == Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.MAX_THREAD_NUM))) {
                                break;
                            }
                        }
                    }
                    //打印文件的数目
//                    logger.info(requestDir + " has " + finalList.size() + " files");

                    if (!finalList.isEmpty()) {
                        for (File file : finalList) {
                            ArrayBlockingQueue<String> jsonBlockingQueue = readFileByLines(file);//解析文件,并移动到success中
                            new VideoDownloadThread(jsonBlockingQueue, file.getName(), (String) RuntimeEnv.getParam(RuntimeEnv.responseDir), Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.timeOut))).execute();
                            new FileTools().moveFileToNewPath(file.getName(), requestDir);

//                            FileUtils.moveFileToDirectory(file, new File(RuntimeEnv.getParam(RuntimeEnv.requestDir) + "success/"), true);
                            logger.info("file name is : " + file.getName() + "  paser sucessfully ");
                        }
//                        Thread.sleep(3000);
                    } else {
//                        logger.info("the localPath---[" + requestDir + "] doesn't hava available file, and sleep 3 seconds.");
                        Thread.sleep(100);
                    }
                } else {
                    logger.info(requestDir + " do not exist.");
                    Thread.sleep(100);
                }
            } catch (Exception ex) {
                logger.error("mathch files failed, cause " + ex.getMessage(), ex);
            }
        }
    }
public ArrayBlockingQueue<String> readFileByLines(File file) {
        ArrayBlockingQueue<String> jsonBlockingQueue = new ArrayBlockingQueue(32);
        BufferedReader reader = null;
        try {
            long begin = System.currentTimeMillis();
            int sum = 0;
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                try {
                    while (!jsonBlockingQueue.offer(tempString)) {
                        Thread.sleep(10);
                    }
                    sum++;
                } catch (InterruptedException ex) {
                    logger.error("add line into " + jsonBlockingQueue + " failed, cause: " + ex.getMessage(), ex);
                }
            }
//            new FileTools().moveFileToNewPath(file.getName(), requestDir);

            long end = System.currentTimeMillis();
            logger.info("readFileByLines--- " + file + " :q " + (end - begin) + " ms, and has " + sum + " records.");
        } catch (Exception ex) {
            logger.error("read " + file + " by line failed, cause: " + ex.getMessage(), ex);
        } finally {
            try {
                reader.close();
            } catch (Exception e) {
                logger.error("close BufferedReader failed, cause: " + e.getMessage(), e);
            }
        }
        return jsonBlockingQueue;
    }
}
